public class BinarySearchTree {

    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }

    public TreeNode root ;

    public void insert(int key) {
        if(root==null){
            root=new TreeNode(key);
        }
        TreeNode parent=null;
        TreeNode cur=root;
        TreeNode node=new TreeNode(key);
        while(cur!=null){
            parent=cur;
            if(key<cur.val){
                cur=cur.left;
            }else if(key>cur.val){
                cur=cur.right;
            }else {
                return;
            }
        }
        if(key<parent.val){
            parent.left=node;
        }else {
            parent.right=node;
        }
    }

    public TreeNode search(int key) {
        TreeNode cur=root;
        while (cur!=null){
            if(cur.val<key){
                cur=cur.right;
            }else if(cur.val==key){
                return cur;
            }else {
                cur=cur.left;
            }
        }
        return null;
    }
    public void remove(int key){
        TreeNode cur=root;
        TreeNode parent=null;
        while(cur!=null){
            parent=cur;
            if(cur.val<key){
                cur=cur.right;
            } else if (cur.val>key) {
                cur=cur.left;
            }else {
                move(parent,cur);
                return;
            }
        }
    }
    public void move(TreeNode parent,TreeNode cur){
        if(cur.left==null){
            if(cur==root){
                root=cur.right;
            } else if (cur==parent.left) {
                parent.left=cur.right;
            }else {
                parent.right=cur.right;
            }
        }else if(cur.right==null){
            if(cur==root){
                root=cur.left;
            } else if (cur==parent.left) {
                parent.left=cur.left;
            }else {
                parent.right=cur.left;
            }
        }else {
            TreeNode targetParent=cur;
            TreeNode target=cur.right;
            while(target.left!=null){
                targetParent=target;
                target=target.left;
            }
            cur.val=target.val;
            if(targetParent.left==target){
                targetParent.left=target.right;
            }else {
                targetParent.right=target.right;
            }
        }
    }
}
